package com.springboot.jwt.config;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.springboot.jwt.config.token.JwtCheckToken;
import com.springboot.jwt.config.token.impl.AdminJwtCheckToken;
import com.springboot.jwt.config.token.impl.BlogJwtCheckToken;
import com.springboot.jwt.dto.JWTHeaderDto;
import com.springboot.jwt.dto.JWTPayload;
import com.springboot.jwt.dto.RequestComm;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0
 * @ClassName JwtCreate
 * @Description
 * Header 头部(标题包含了令牌的元数据，并且包含签名和/或加密算法的类型)
 * Payload 负载
 * Signature 签名/签证
 * @Author zyj
 * @date 2021/4/1 13:33
 **/
@Component
@Slf4j
public class JwtUtil {

	@Resource
	private AdminJwtCheckToken adminJwtCheckToken;

	@Resource
	private BlogJwtCheckToken blogJwtCheckToken;

	/**
	 * @Description
	 * @Author zyj
	 * @Date 2021/4/1 15:30
	 * @param jwtHeaderDto
	 * @param jwtPayload
	 * @param signature
	 * @return java.lang.String
	 **/
	public String jwtCreate(JWTHeaderDto jwtHeaderDto, JWTPayload jwtPayload, String signature) throws Exception{
		JWTCreator.Builder builder =  JWT.create();

		//jwt header头信息
		Map<String, Object> headerMap = new HashMap<>();
		headerMap.put("alg", jwtHeaderDto.getAlg());
		headerMap.put("typ", jwtHeaderDto.getTyp());
		builder.withHeader(headerMap);

		//jwt Payload
		builder.withIssuer(jwtPayload.getIss());
		builder.withSubject(jwtPayload.getSub());
		builder.withAudience(jwtPayload.getAud());
		builder.withExpiresAt(jwtPayload.getExp());
		builder.withNotBefore(jwtPayload.getNbf());
		builder.withIssuedAt(jwtPayload.getIat());

		//jwt sign
		String sign = builder.sign(Algorithm.HMAC256(signature));
		return sign;

	}

	/**
	 * 方法描述 获取token校验类型
	 * @since: 1.0
	 * @param
	 * @return: JwtCheckToken
	 * @author: zyj
	 * @date: 2024/4/10
	 */
	public JwtCheckToken getCheckTokenType(String type){
		if(RequestComm.REQUEST_TOKEN_TYPE_BLOGUSER.getName().equals(type)){
			return blogJwtCheckToken;
		}else {
			return adminJwtCheckToken;
		}
	}

}
